using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.SessionState;
using Krystalware.SlickUpload;
using Krystalware.SlickUpload.Providers;
using Krystalware.SlickUpload.Configuration;

/// <summary>
/// An <see cref="IUploadStreamProvider" /> that streams each file into its own .zip file.
/// </summary>
public class UploadStreamProvider : IUploadStreamProvider
{
    /// <summary>
    /// The <see cref="UploadedFile.LocationInfo" /> key used to store the server filename value.
    /// </summary>
    public const string FileNameKey = "fileName";

    public Stream GetInputStream(UploadedFile file)
    {
        FileStream fileS = null;        
        try
        {
            string path = GetZipPath(file);
            fileS = File.OpenRead(path);
            return fileS;
        }
        catch
        {
            if (fileS != null)
                fileS.Dispose();
            return null;
        }
    }

    public Stream GetOutputStream(UploadedFile file)
    {
        FileStream fileS = null;
        try
        {
            string outputPath = GetZipPath(file);
            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
            fileS = File.OpenWrite(outputPath);
            file.LocationInfo[FileNameKey] = outputPath;
            return fileS;
        }
        catch
        {
            if (fileS != null)
                fileS.Dispose();
            return null;
        }
    }

    public void RemoveOutput(UploadedFile file)
    {
        string path = GetZipPath(file);
        if (File.Exists(path))
            File.Delete(path);
    }

    string GetZipPath(UploadedFile file)
    {
        string location = SessionManager.UploadURL;        
        return Path.Combine(HttpContext.Current.Server.MapPath(location), file.ClientName);
    }
}